package com.gwctv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gwctv.constant.MessageConstant;
import com.gwctv.dto.UserLoginDto;
import com.gwctv.entity.User;
import com.gwctv.exception.LoginFailedException;
import com.gwctv.mapper.UserMapper;
import com.gwctv.properties.WeChatProperties;
import com.gwctv.service.UserService;
import com.gwctv.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Sevice 将该程序标识为业务逻辑处理层
 * @Slf4j 将日志输出到控制台
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    //自动注入WeChatProperties配置类对象
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    //微信接口服务地址（此处定义为常量）
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public User wxLogin(UserLoginDto userLoginDto) {

        //1.调用微信接口服务，获得当前用户的openid
        String openid = getOpenid(userLoginDto.getCode());

        //2.判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3.判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);
        //4.如果是新用户，自动完成注册
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //将新用户保存到user表中
            userMapper.insert(user);
        }

        //5.返回用户对象
        return user;
    }

    /**
     * 将wxLoging方法中的代码进行封装
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //1.调用微信接口服务，获得当前用户的openid
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN,map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
